package com.wisezone.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.wisezone.demo0304.*;
import org.apache.commons.dbutils.QueryRunner;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

public class MyDBUtils {
    static DruidDataSource dataSource=null;

    static {
        Properties properties= new Properties();
        try
        {
            //加载数据库配置文件
            properties.load(MyDBUtils.class.getClassLoader().getResourceAsStream("com/wisezone/db.properties"));
            //直接通过Properties对象加载数据库阿里连接池
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        }catch (IOException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据阿里数据连接池取得连接对象
     * @return
     * @throws SQLException
     */
    private Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 查询数据表方法
     * @param sql
     * @param params
     * @param <T>
     * @return
     * @throws SQLException
     */
    public <T> List<T> query(String sql, Object[] params)throws SQLException{
        QueryRunner queryRunner =new QueryRunner();
        return queryRunner.query(this.getConnection(),sql,new My<T>(),params);
    }
}
